﻿@inject IJSRuntime JSRuntime
@inject NavigationManager NavigationManager
@inject IMarkdownComponentService Service

<article @ref="markdownContent" class="@Class" style="@Style">
    @((MarkupString)Html)
</article>

@code {
    [Parameter]
    public string Value { get; set; } = "";

    [Parameter]
    public string Style { get; set; } = "";

    [Parameter]
    public string Class { get; set; } = "";

    private string Html = "";

    private ElementReference markdownContent;

    private string BaseUrl { get; set; }

    protected override void OnInitialized()
    {
        BaseUrl = NavigationManager.ToBaseRelativePath(NavigationManager.Uri);
        var ind = BaseUrl.IndexOf('#');
        if (ind >= 0)
            BaseUrl = BaseUrl.Remove(ind);
    }

    protected override async Task OnParametersSetAsync()
    {
        Html = await Service.RenderHtml(Value);
        await base.OnParametersSetAsync();
    }

    public async Task Rerender()
    {
        Html = await Service.RenderHtml(Value);
        StateHasChanged();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (Service.EnableCodeHighlight)
        {
            await JSRuntime.InvokeVoidAsync("StardustDL_RazorComponents_Markdown.highlight", markdownContent);
        }
        if (Service.EnableMathematics)
        {
            await JSRuntime.InvokeVoidAsync("StardustDL_RazorComponents_Markdown.math", markdownContent);
        }
        if (Service.EnableDiagrams)
        {
            await JSRuntime.InvokeVoidAsync("StardustDL_RazorComponents_Markdown.diagram", markdownContent);
        }
        await JSRuntime.InvokeVoidAsync("StardustDL_RazorComponents_Markdown.fixAnchor", markdownContent, BaseUrl);
    }
}
